<template>
  <div class="search-page">
    <div class="search-header">
      <div class="back-button" @click="goBack">
        <img src="@/assets/icon/返回.png" alt="">
      </div>
      <div class="search-input">
        <el-input
          v-model="searchKey"
          placeholder="搜索歌曲、歌手、专辑"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <img src="@/assets/icon/tabar/sousuo.png" class="search-icon" />
          </template>
        </el-input>
      </div>
    </div>

    <div class="search-tabs">
      <div 
        v-for="(tab, index) in tabs" 
        :key="index" 
        :class="['tab-item', { active: currentTab === tab.value }]"
        @click="changeTab(tab.value)"
      >
        {{ tab.label }}
      </div>
    </div>

    <div class="search-results" v-if="searchResults.length">
      <div v-for="(item, index) in searchResults" :key="index" class="result-item" @click="playMusic(item)">
        <template v-if="currentTab === 0">
          <!-- 歌曲搜索结果 -->
          <div class="song-info">
            <div class="song-title">{{ item.songname }}</div>
            <div class="song-artist">
              {{ item.singer && item.singer[0] ? item.singer[0].name : '未知歌手' }}
              <span v-if="item.albumname"> · {{ item.albumname }}</span>
            </div>
          </div>
          <div class="play-icon">
            <i class="el-icon-video-play"></i>
          </div>
        </template>
        
        <template v-else-if="currentTab === 2">
          <!-- 歌单搜索结果 -->
          <img :src="getImageUrl(item)" class="playlist-cover">
          <div class="playlist-info">
            <div class="playlist-title">{{ item.dissname || item.title || '未知歌单' }}</div>
            <div class="playlist-creator">{{ item.creator && item.creator.name ? item.creator.name : '未知创建者' }}</div>
          </div>
        </template>
        
        <template v-else-if="currentTab === 8">
          <!-- 专辑搜索结果 -->
          <img :src="getAlbumImageUrl(item)" class="playlist-cover">
          <div class="playlist-info">
            <div class="playlist-title">{{ item.albumname || '未知专辑' }}</div>
            <div class="playlist-creator">{{ item.singer && item.singer[0] ? item.singer[0].name : '未知歌手' }}</div>
          </div>
        </template>
        
        <template v-else-if="currentTab === 9">
          <!-- 歌手搜索结果 -->
          <img :src="getSingerImageUrl(item)" class="playlist-cover singer-avatar">
          <div class="playlist-info">
            <div class="playlist-title">{{ item.singer_name || item.name || '未知歌手' }}</div>
            <div class="playlist-creator">歌手</div>
          </div>
        </template>
      </div>
    </div>
    
    <div class="no-results" v-else-if="hasSearched">
      没有找到相关结果
    </div>
    
    <div class="search-placeholder" v-else>
      <div class="placeholder-text">搜索你喜欢的音乐</div>
      <div class="hot-keywords" v-if="hotKeywords.length">
        <div class="hot-title">热门搜索</div>
        <div class="keyword-list">
          <div 
            v-for="(keyword, index) in hotKeywords" 
            :key="index" 
            class="keyword-item"
            @click="searchByKeyword(keyword)"
          >
            {{ keyword }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { musicApi } from '@/api/music'
import { usePlayerStore } from '@/store'

const route = useRoute()
const router = useRouter()
const playerStore = usePlayerStore()
const searchResults = ref([])
const hasSearched = ref(false)
const currentTab = ref(0)
const searchKey = ref('')
const hotKeywords = ref(['周杰伦', '林俊杰', '陈奕迅', '薛之谦', '华语流行', '抖音热歌', '经典老歌'])

const tabs = [
  { label: '单曲', value: 0 },
  { label: '歌单', value: 2 },
  { label: '专辑', value: 8 },
  { label: '歌手', value: 9 },
  { label: 'MV', value: 12 }
]

const goBack = () => {
  router.back()
}

const changeTab = (tabValue) => {
  currentTab.value = tabValue
  if (searchKey.value) {
    handleSearch()
  }
}

const handleSearch = () => {
  if (searchKey.value.trim()) {
    searchWithParams(searchKey.value, 1, 20, currentTab.value)
  }
}

const searchByKeyword = (keyword) => {
  searchKey.value = keyword
  handleSearch()
}

const getImageUrl = (item) => {
  if (item.imgurl) return item.imgurl
  if (item.cover) return item.cover
  return 'https://y.qq.com/mediastyle/global/img/album_300.png'
}

const getAlbumImageUrl = (item) => {
  if (item.albumid && item.albummid) {
    return `https://y.qq.com/music/photo_new/T002R300x300M000${item.albummid}.jpg`
  }
  return 'https://y.qq.com/mediastyle/global/img/album_300.png'
}

const getSingerImageUrl = (item) => {
  if (item.singer_mid || item.mid) {
    const mid = item.singer_mid || item.mid
    return `https://y.qq.com/music/photo_new/T001R300x300M000${mid}.jpg`
  }
  return 'https://y.qq.com/mediastyle/global/img/singer_300.png'
}

const playMusic = async (item) => {
  if (currentTab.value === 0 && item.songmid) {
    try {
      // 获取歌曲播放地址
      const response = await musicApi.getSongUrl(item.songmid)
      console.log('获取到的歌曲URL响应:', response)
      
      if (response && response.data) {
        // 处理URL，确保获取到的是字符串
        let songUrl = ''
        
        // 检查响应数据的结构
        if (typeof response.data === 'string') {
          songUrl = response.data
        } else if (response.data.url) {
          songUrl = response.data.url
        } else if (typeof response.data.data === 'string') {
          songUrl = response.data.data
        } else if (response.data.data && response.data.data.url) {
          songUrl = response.data.data.url
        }

        if (!songUrl) {
          console.error('无法从响应中提取URL:', response.data)
          return
        }

        // 确保URL是有效的HTTP(S)链接
        if (!songUrl.startsWith('http')) {
          songUrl = `https://${songUrl}`
        }
        
        console.log('解析后的歌曲URL:', songUrl)
        
        // 构建完整的歌曲数据对象
        const songData = {
          songmid: item.songmid,
          songname: item.songname || '未知歌曲',
          singer: item.singer || [{ name: '未知歌手' }],
          albumname: item.albumname || '未知专辑',
          albummid: item.albummid || '',
          cover: item.albummid 
            ? `https://y.qq.com/music/photo_new/T002R300x300M000${item.albummid}.jpg`
            : 'https://y.qq.com/mediastyle/global/img/album_300.png',
          url: songUrl
        }
        
        console.log('传递给播放器的歌曲数据:', songData)
        
        // 直接使用已导入的 playerStore，不需要重新导入
        playerStore.playSong(songData)
      }
    } catch (error) {
      console.error('获取歌曲播放地址失败:', error)
    }
  } else if (currentTab.value === 2 && item.dissid) {
    // 查看歌单
    router.push({
      path: '/playlist',
      query: { id: item.dissid }
    })
  }
}

const searchWithParams = async (key, pageNo = 1, pageSize = 20, t = 0) => {
  if (!key) return
  
  try {
    // 修改回使用 search 方法
    const response = await musicApi.search({
      key,
      pageNo,
      pageSize,
      t
    })
    
    console.log('搜索响应:', response)
    
    // 安全地访问数据
    if (response && response.data && response.data.data && response.data.data.list) {
      searchResults.value = response.data.data.list
    } else if (response && response.data && response.data.list) {
      searchResults.value = response.data.list
    } else {
      searchResults.value = []
    }
    
    hasSearched.value = true
  } catch (error) {
    console.error('搜索失败:', error)
    searchResults.value = []
    hasSearched.value = true
  }
}

const searchWithCurrentParams = () => {
  const { key, pageNo = 1, pageSize = 20, t = 0 } = route.query
  
  if (key) {
    searchKey.value = key
    currentTab.value = Number(t)
    searchWithParams(key, pageNo, pageSize, t)
  }
}

// 监听路由变化
watch(() => route.query, () => {
  searchWithCurrentParams()
}, { immediate: true })

// 初始化
onMounted(() => {
  searchWithCurrentParams()
})
</script>

<style lang="scss" scoped>
.search-page {
  padding: 15px;
  
  .search-header {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    
    .back-button {
      width: 30px;
      height: 30px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 10px;
      cursor: pointer;
      
      img {
        width: 20px;  // 调整图标大小
        height: 20px;  // 保持宽高比
        opacity: 0.8;  // 稍微调整透明度使其看起来更柔和
        
        &:active {
          opacity: 0.6;  // 点击时的效果
        }
      }
    }
    
    .search-input {
      flex: 1;
      
      .search-icon {
        width: 18px;
        height: 18px;
      }
      
      :deep(.el-input__wrapper) {
        border-radius: 20px;
        background-color: #f5f5f5;
        box-shadow: none;
        padding: 0 15px;
      }
      
      :deep(.el-input__inner) {
        height: 36px;
        font-size: 14px;
      }
    }
  }
  
  .search-tabs {
    display: flex;
    overflow-x: auto;
    margin-bottom: 15px;
    
    &::-webkit-scrollbar {
      display: none;
    }
    
    .tab-item {
      padding: 8px 15px;
      margin-right: 10px;
      white-space: nowrap;
      font-size: 14px;
      color: #666;
      border-radius: 15px;
      background-color: #f5f5f5;
      cursor: pointer;
      
      &.active {
        color: #fff;
        background-color: #31c27c;
      }
    }
  }
  
  .search-results {
    .result-item {
      display: flex;
      align-items: center;
      padding: 12px 0;
      border-bottom: 1px solid #f5f5f5;
      cursor: pointer;
      
      .song-info, .playlist-info {
        flex: 1;
        overflow: hidden;
      }
      
      .song-title, .playlist-title {
        font-size: 15px;
        margin-bottom: 5px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      
      .song-artist, .playlist-creator {
        font-size: 12px;
        color: #999;
      }
      
      .play-icon {
        width: 30px;
        height: 30px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #31c27c;
      }
      
      .playlist-cover {
        width: 50px;
        height: 50px;
        border-radius: 4px;
        margin-right: 10px;
        object-fit: cover;
      }
      
      .singer-avatar {
        border-radius: 50%;
      }
    }
  }
  
  .no-results {
    text-align: center;
    padding: 30px 0;
    color: #999;
    font-size: 14px;
  }
  
  .search-placeholder {
    padding: 20px 0;
    
    .placeholder-text {
      text-align: center;
      color: #999;
      font-size: 14px;
      margin-bottom: 30px;
    }
    
    .hot-keywords {
      .hot-title {
        font-size: 16px;
        font-weight: 500;
        margin-bottom: 15px;
      }
      
      .keyword-list {
        display: flex;
        flex-wrap: wrap;
        
        .keyword-item {
          padding: 6px 12px;
          background-color: #f5f5f5;
          border-radius: 15px;
          margin-right: 10px;
          margin-bottom: 10px;
          font-size: 13px;
          color: #333;
          cursor: pointer;
          
          &:hover {
            background-color: #e5e5e5;
          }
        }
      }
    }
  }
}
</style>
